using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;

namespace PinTuGame
{
    public class GameRecord
    {
        public string PlayerName { get; set; }
        public string Difficulty { get; set; }
        public TimeSpan PlayTime { get; set; }
        public int MoveCount { get; set; }
        public DateTime CompletionDate { get; set; }
        public string ImageName { get; set; }

        public GameRecord(string playerName, string difficulty, TimeSpan playTime, int moveCount, string imageName)
        {
            PlayerName = playerName;
            Difficulty = difficulty;
            PlayTime = playTime;
            MoveCount = moveCount;
            CompletionDate = DateTime.Now;
            ImageName = imageName;
        }
    }

    public class Leaderboard
    {
        private List<GameRecord> records;
        private readonly string filePath = "leaderboard.json";

        public Leaderboard()
        {
            LoadRecords();
        }

        public void AddRecord(GameRecord record)
        {
            records.Add(record);
            SaveRecords();
        }

        public List<GameRecord> GetTopRecords(string difficulty, int count = 10)
        {
            return records
                .Where(r => r.Difficulty == difficulty)
                .OrderBy(r => r.PlayTime)
                .ThenBy(r => r.MoveCount)
                .Take(count)
                .ToList();
        }

        public List<GameRecord> GetAllRecords()
        {
            return records.OrderByDescending(r => r.CompletionDate).ToList();
        }

        public void ClearRecords()
        {
            records.Clear();
            SaveRecords();
        }

        private void LoadRecords()
        {
            try
            {
                if (File.Exists(filePath))
                {
                    string json = File.ReadAllText(filePath);
                    records = JsonSerializer.Deserialize<List<GameRecord>>(json) ?? new List<GameRecord>();
                }
                else
                {
                    records = new List<GameRecord>();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载排行榜失败: {ex.Message}");
                records = new List<GameRecord>();
            }
        }

        private void SaveRecords()
        {
            try
            {
                string json = JsonSerializer.Serialize(records, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(filePath, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存排行榜失败: {ex.Message}");
            }
        }
    }
} 